package com.junmeng.libfloating.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.FrameLayout
import com.junmeng.libfloating.util.Log
import kotlin.math.abs

/**
 * 用于解决ViewPager2中使用RecyclerView时滑到底部再往上滑时会触发ViewPager2的onPageSelected回调
 * 用法：用作可滚动view(如RecyclerView)的直接父view,可滚动view是此View的唯一子View
 */
class NestedScrollableMediateContainer @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
    companion object {
        const val TAG = "NestedScrollableMediateContainer"
    }

    private var initialX = 0f
    private var initialY = 0f

    override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
        if (childCount == 1) {
            when (e.action) {
                MotionEvent.ACTION_DOWN -> {
                    initialX = e.x
                    initialY = e.y
                }

                MotionEvent.ACTION_MOVE -> {
                    val dx = e.x - initialX
                    val dy = e.y - initialY
                    //如果是子view已经滚到底或滚到顶了
//                if (!canScrollVertically(1) || !canScrollVertically(-1)) {
//                    if (abs(dx) < abs(dy)) {
//                        requestDisallowInterceptTouchEvent(true)
//                    }
//                }
                    val canScrollUp = getChildAt(0).canScrollVertically(1)
                    val canScrollDown = getChildAt(0).canScrollVertically(-1)
                    Log.i(
                        TAG,
                        "能否向上滚动=${canScrollUp}，能否向下滚动=${canScrollDown},dx=${dx},dy=${dy}"
                    )
                    if (abs(dy) > abs(dx)) {
                        if (canScrollUp || canScrollDown) {
                            requestDisallowInterceptTouchEvent(true)
                        }
                    }
                }
            }
        }

        return super.onInterceptTouchEvent(e)
    }

}